<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="treeName"
            placeholder="请输入查询名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
<!--        <el-tag>请选择院系/专业</el-tag>-->
        <div class="head-container">
          <el-tree
            ref="tree"
            node-key="id"
            :data="leftTreeOptions"
            :props="defaultProps"
            :filter-node-method="filterNode"
            :expand-on-click-node="false"
            highlight-current
            :default-expanded-keys="defaultExpandedKeys"
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
          <el-form-item label="题库" prop="courseSubject">
            <el-input
              v-model="queryParams.courseSubject"
              placeholder="请输入题库名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:juanCourse:add']" type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              :disabled="!queryParams.department"
            >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['juan:juanQuestion:import']" type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
              >导入题目数据包
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:juanCourse:export']" type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
            >导出Excel
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:juanCourse:add']" type="primary" plain icon="el-icon-copy-document" size="mini" @click="mergerOpen = true"
            >合并
            </el-button>
          </el-col>
          <right-toolbar :show-search.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="juanCourseList" @selection-change="handleSelectionChange">
         <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="题库编号" align="center" prop="courseCode" />
          <el-table-column label="题库名称" align="center" prop="courseSubject" />
          <el-table-column label="题库类型" align="center" prop="courseType" >
            <template slot-scope="scope">
              <dict-tag :options="dict.type.course_type" :value="scope.row.courseType" />
            </template>
          </el-table-column>
          <el-table-column label="建设方式" align="center" prop="courseConstruction">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.construction" :value="scope.row.courseConstruction" />
            </template>
          </el-table-column>
          <el-table-column label="题卷量" align="center" prop="courseCount" />
          <el-table-column label="首建日期" align="center" prop="createdTime" width="100">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createdTime, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column label="修订日期" align="center" prop="updatedTime" width="100">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.updatedTime, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column label="负责人" align="center" prop="person"/>
          <el-table-column label="适用院系" align="center" prop="departName" />
          <el-table-column label="适用层次类型" align="center" prop="courseHierarchy">
            <template slot-scope="scope">
                <dict-tag :options="dict.type.hierarchy" :value="scope.row.courseHierarchy.split(',')" />
            </template>
          </el-table-column>
          <el-table-column label="适用专业" align="center" prop="majorName" />
          <el-table-column label="适用课程" align="center" prop="course" />
<!--          <el-table-column label="课程描述" align="center" prop="courseDes" />-->
<!--                <el-table-column label="创建人" align="center" prop="createdBy" />-->
<!--                <el-table-column label="更新人" align="center" prop="updatedBy" />-->
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
            <template slot-scope="scope">
              <el-button v-hasPermi="['system:juanCourse:edit']" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button v-hasPermi="['system:juanCourse:remove']" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
<!--              <el-button v-hasPermi="['system:juanCourse:bindUser']" size="mini" type="text" icon="el-icon-user" @click="handleBindUser(scope.row)">用户绑定</el-button>-->
              <!-- <el-button v-hasPermi="['system:juanCourse:bindUser']" size="mini" type="text" icon="el-icon-user" @click="handleTKExport(scope.row)">导出题库</el-button> -->
              <el-button
                v-hasPermi="['system:juanCourse:export']"
                size="mini"
                type="text"
                icon="el-icon-download"
                @click="handleExportJson(scope.row)"
                >导出数据包
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

      </el-col>
    </el-row>

    <!-- 添加或修改课程对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="题库编号" prop="courseCode">
          <el-input maxlength="30" v-model="form.courseCode" placeholder="自动生成" :disabled="true" />
        </el-form-item>
        <el-form-item label="院系专业" prop="departMajor">
          <el-cascader style="width: 100%" placeholder="请选择院系专业" v-model="form.departMajor" :options="cascaderOptions" :props="departMajorProps" ></el-cascader>
        </el-form-item>
        <el-form-item label="层次类型" prop="courseHierarchy">
          <el-select v-model="form.courseHierarchy" multiple placeholder="请选择层次类型" clearable>
            <el-option v-for="(dict, index) in dict.type.hierarchy" :key="index" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程名称" prop="course">
          <el-input maxlength="30" v-model="form.course" placeholder="请输入课程名称" />
        </el-form-item>

        <el-form-item label="题库名称" prop="courseSubject">
          <el-input maxlength="30" v-model="form.courseSubject" placeholder="请输入题库名称" />
        </el-form-item>
        <el-form-item label="题库类型" prop="courseType">
          <el-select v-model="form.courseType" placeholder="请选择题库类型" clearable>
            <el-option v-for="(dict, index) in dict.type.course_type" :key="index" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="建设方式" prop="courseConstruction">
          <el-select v-model="form.courseConstruction" placeholder="请选择建设方式" clearable>
            <el-option v-for="(dict, index) in dict.type.construction" :key="index" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="题卷量" prop="courseCount">
          <el-input maxlength="30" v-model="form.courseCount" placeholder="请输入题卷量" />
        </el-form-item>
        <el-form-item label="负责人" prop="person">
          <el-input maxlength="30" v-model="form.person" placeholder="请输入负责人" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="2"
        accept=".json"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
      <!-- :action="upload.url + '?updateSupport=' + upload.updateSupport" -->
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip text-center">
          <span>仅允许导入json格式文件。</span>
          <!-- <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" href = "http://221.234.44.30:8078/juan/file/courseTemplate.xlsx"
          >下载模板</el-link
          > -->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- this.queryParams.department -->

    <el-dialog title="合并题库" :visible.sync="mergerOpen" width="55%" append-to-body :before-close="mergerClose" class="common-dialog">
      <merger v-if="mergerOpen" :department-id="queryParams.department" @close="mergerClose" @success="mergerSuccess"></merger>
    </el-dialog>
  </div>
</template>

<script>
import { listJuanCourse, getJuanCourse,getJuanCourseCode, delJuanCourse, addJuanCourse, updateJuanCourse } from "@/api/system/juanCourse";
import { leftTree } from '../../../api/system/juanCourse';
import { getDeptTree } from "@/api/system/user";
import { getToken } from "@/utils/auth";
import request from "@/utils/request";
import Merger from './merger';

export default {
  name: "JuanCourse",
  components: { Merger },
  dicts: ['hierarchy','course_type','construction'],
  data() {
    return {
      treeSelected: [],
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程表格数据
      juanCourseList: [],
      // 弹出层标题
      title: "",
      //专业名称
      treeName: undefined,
      // 左侧树选项
      leftTreeOptions: undefined,
      cascaderOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        //url: process.env.VUE_APP_BASE_API + "/system/juanCourse/importFile",
        url: "http://127.0.0.1:8075/juan/juanQuestion/importjson",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        department: undefined,
        majorId: undefined,
        departId: undefined,
        courseId: undefined,
        courseCode: undefined,
        courseSubject: undefined,
        course: undefined,
        courseType: undefined,
        courseConstruction: undefined,
        courseCount: undefined,
        courseHierarchy: undefined,
        courseDes: undefined,
        createdBy: undefined,
        createdTime: undefined,
        updatedBy: undefined,
        updatedTime: undefined,
        person: undefined,
      },
      // 表单参数
      isEdit: true,
      form: {},
      defaultProps: {
        children: "children",
        //label: "treeName",
        label: "label",
      },
      defaultExpandedKeys: [],
      // 表单校验
      rules: {
        courseId: [{ required: true, message: "ID不能为空", trigger: "blur" }],
        majorId: [{ required: true, message: "专业ID不能为空", trigger: "blur" }],
        departId: [{ required: true, message: "院系ID不能为空", trigger: "blur" }],
        courseSubject: [{ required: true, message: "题库名称不能为空", trigger: "blur" }],
        // course: [{ required: true, message: "课程名称不能为空", trigger: "blur" }],
        // courseType: [{ required: true, message: "课程类型不能为空", trigger: "blur" }],
        // courseGrade: [{ required: true, message: "年级不能为空", trigger: "blur" }],
        // courseTerm: [{ required: true, message: "学期不能为空", trigger: "blur" }],
        // coursePeriod: [{ required: true, message: "课时不能为空", trigger: "blur" }],
        // courseDes: [{ required: true, message: "课程描述不能为空", trigger: "blur" }],
        // departMajor: [{ required: true, message: "专业院系不能为空", trigger: "blur" }],
      },
      departMajorProps: {
        label: 'treeName',
        value: 'id',
        multiple: true
      },
      mergerOpen: false
    };
  },
  watch: {
    // 根据名称筛选知识点树
    treeName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getList();
    this.getDeptTree();
    this.getLeftTree();
  },
  methods: {
    /** 查询课程列表 */
    getList() {
      this.loading = true;
      listJuanCourse(this.queryParams).then((response) => {
        this.juanCourseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询树结构 */
    getDeptTree() {
      getDeptTree().then((response) => {
        this.leftTreeOptions = response.data;
        this.renderTree(this.leftTreeOptions, 1);
        this.dgTree(this.leftTreeOptions, 3);

        this.$nextTick(() => {
          if (response.data && response.data.length > 0) {
            this.$refs.tree.setCurrentKey(response.data[0].id); // 默认选中节点第一个
            this.treeSelected = null; // 用户未点击专业，则禁止新增
          }
        });
        this.defaultExpandedKeys = response.data.map((item) => {
          return item.id;
        });
      });
    },
    //递归* 添加level
    renderTree(data, level) {
      return data.map((item) => {
        item.level = level;
        if (item.children) {
          this.renderTree(item.children, level + 1);
        }
      });
    },
    dgTree(list) {
      let ts = [3, 4];
      for (let i = 0; i < list.length; i++) {
        if (!list[i].children) {
          if (ts.indexOf(list[i].level) === -1) {
            list.splice(i, 1);
            i--;
            //删完了
            if (!list.length) {
              return true;
            }
          }
        } else {
          let isDelAll = this.dgTree(list[i].children);
          if (isDelAll) i--;
        }
      }
    },

    /** 查询院系专业 */
    getLeftTree() {
      leftTree().then((response) => {
        this.cascaderOptions = response.data;
        this.$nextTick(()=>{
          if (response.data && response.data.length > 0) {
            this.$refs.tree.setCurrentKey(response.data[0].id); // 默认选中节点第一个
            this.treeSelected = null; // 用户未点击专业，则禁止新增
          }
        })
      });
    },

    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.treeName.indexOf(value) !== -1;
    },
    handleNodeClick(data, node) {
      this.queryParams.department = data.id;
      if (!node.childNodes.length) {
        this.treeSelected = true;
      } else {
        this.treeSelected = null;
      }
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        courseId: undefined,
        majorId: undefined,
        departId: undefined,
        courseCode: undefined,
        courseSubject: undefined,
        courseType: undefined,
        courseConstruction: undefined,
        courseCount: undefined,
        courseHierarchy: undefined,
        courseDes: undefined,
        createdBy: undefined,
        createdTime: undefined,
        updatedBy: undefined,
        updatedTime: undefined,
        departMajor: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.courseId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      getJuanCourseCode({
        department:this.queryParams.department
      }).then((res) => {
        this.form.courseCode = res;
      });
      // if (this.leftTreeOptions.length > 0 && this.treeSelected && this.treeSelected.length > 0) {
      //   this.form.departMajor = [...this.treeSelected]
      // }
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const courseId = row.courseId || this.ids;
      getJuanCourse(courseId).then((response) => {
        this.loading = false;
        this.form = response.data;
        if (this.form.departId && this.form.majorId) {
          let departIds = this.form.departId.split(',')
          let majorIds = this.form.majorId.split(',')

          this.form.departMajor = [];
          for (let i = 0; i < departIds.length; i++) {
            this.form.departMajor && this.form.departMajor.push([departIds[i], majorIds[i]])
          }
        }

        if(this.form.courseHierarchy) {
          this.form.courseHierarchy = this.form.courseHierarchy.split(',')
        }
        this.open = true;
        this.title = "修改题库";
      });
    },
    /** 用户绑定按钮操作 */
    handleBindUser(row){
      const courseId = row.courseId;
      this.$router.push("/message/juanCourse/bindUser/" + courseId);
    },
    /** 提交按钮 */
    submitForm() {
      let departIds = []
      let majorIds = []
      let departMajor = this.form.departMajor;
      if(departMajor && departMajor.length > 0) {
        for (let i = 0; i < departMajor.length; i++) {
          departIds.push(departMajor[i][0])
          majorIds.push(departMajor[i][1])
        }
      }
      this.form.departId = departIds.join(',')
      this.form.majorId = majorIds.join(',')

      let option = {
        ...this.form,
        courseHierarchy: this.form.courseHierarchy ? this.form.courseHierarchy.join(',') : ''
      }

      this.$refs["form"].validate((valid) => {
        if (valid) {

          this.buttonLoading = true;
          option.department = this.queryParams.department;
          if (option.courseId != null) {
            updateJuanCourse(option)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addJuanCourse(option)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const courseIds = row.courseId || this.ids;
      this.$modal
        .confirm('是否确认删除？')
        .then(() => {
          this.loading = true;
          return delJuanCourse(courseIds);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/juanCourse/export",
        {
          ...this.queryParams,
        },
        `题库 ${new Date().toLocaleString()}.xlsx`
      );
    },
    /** 导出数据包按钮操作 */
    handleExportJson(data) {
      request({
        url: "juan/juanQuestion/exportjson",
        method: "post",
        data: {
          courseId: data.courseId,
        },
      }).then((res) => {
        this.saveJSON(res, data.courseSubject + `juanQuestion.json`);
      });
    },
    saveJSON(data, filename) {
      if (!data) {
        return;
      }
      if (!filename) {
        filename = "json.json";
      }
      if (typeof data === "object") {
        data = JSON.stringify(data, undefined, 4);
      }
      let blob = new Blob([data], { type: "text/json" });
      let e = document.createEvent("MouseEvents");
      let a = document.createElement("a");
      a.download = filename;
      a.href = window.URL.createObjectURL(blob);
      a.dataset.downloadurl = ["text/json", a.download, a.href].join(":");
      e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
      a.dispatchEvent(e);
    },
    /** 导出题库操作 */
    handleTKExport(row) {
      let courseId = row.courseId
      this.download(
        "juan/juanQuestion/exportjson",
        {
          courseId
        },
        `juanCourse_${new Date().getTime()}.json`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "题目导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      // this.download("http://221.234.44.30:8078/juan/file/departTemplate.xlsx", {}, `template_${new Date().getTime()}.xlsx`);
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + "导入成功！" + "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    mergerClose() {
      this.mergerOpen = false
    },
    mergerSuccess() {
      this.mergerClose();
      this.handleQuery();
    }
  },
};
</script>
